package com.atguigu.p2.service;

import com.atguigu.p2.bean.Customer;

/**
 *
 *      CustomerList为Customer对象的管理模块，内部用数组管理一组Customer对象，并提供相应的添加、修改、删除和遍历方法， 供CustomerView调用
 *
 * @author : leimingchao
 * @date Date : 2021年08月21日 15:27
 */
public class CustomerList {

    /**
     * 用来保存客户对象的数组
     */
    private Customer[] customers;

    /**
     * 记录客户对象的数量
     */
    private int total;

    public CustomerList() {

    }

    public CustomerList(int totalCustomer) {
        customers = new Customer[totalCustomer];
    }

    public boolean addCustomer(Customer customer) {
        if (total >= customers.length) {
            return false;
        }
        customers[total++] = customer;
        return true;
    }

    public boolean replaceCustomer(int index, Customer customer) {
        if (index < 0 || index >= total) {
            return false;
        }

        customers[index] = customer;
        return true;
    }

    public boolean deleteCustomer(int index) {
        if (index < 0 || index >= total) {
            return false;
        }
        for (int i = index ; i < total - 1 ; i++) {
            customers[i] = customers[i + 1];
        }
        //最后有数据的元素置空
        customers[--total] = null;
        return true;
    }

    public Customer[] getAllCustomers() {
        Customer[] cust = new Customer[total];
        for (int i = 0; i < cust.length; i++) {
            cust[i] = customers[i];
        }
        return cust;
    }

    public Customer getCustomer(int index) {
        if (index < 0 || index >= total) {
            return null;
        }
        return customers[index];
    }

    public int getTotal() {
        return total;
    }
}
